import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'package:flutter_login/flutter_login.dart';
import '/utils/regex.dart';
import '/plugin/dio_new/dio_new.dart';
import 'package:get/get.dart';
import '/router/router.dart';
import 'dart:io';
import 'package:device_info/device_info.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '/utils/api.dart';
import 'package:owner_flutter/utils/localStorage.dart';
import 'package:owner_flutter/main.dart';

class Login extends StatefulWidget {
  const Login({Key? key}) : super(key: key);

  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  late HttpClient dio;
  Duration get loginTime => Duration(milliseconds: 2250);

  static final DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
  String deviceId = '';
  late SharedPreferences prefs;
  Future<void> initPlatformState() async {
    Map<String, dynamic> deviceData = <String, dynamic>{};
    prefs = await SharedPreferences.getInstance();
    try {
      if (Platform.isAndroid) {
        AndroidDeviceInfo androidInfo = await deviceInfoPlugin.androidInfo;
        deviceId = androidInfo.androidId;
        // 本地存储
        prefs.setString(LocalStorage.DEVICEID, androidInfo.androidId);
        // deviceData = DeviceInfo.readAndroidBuildData(androidInfo);
        // print(deviceData);
      } else if (Platform.isIOS) {
        IosDeviceInfo iosInfo = await deviceInfoPlugin.iosInfo;
        deviceId = iosInfo.identifierForVendor;
        // 本地存储
        prefs.setString(LocalStorage.DEVICEID, iosInfo.identifierForVendor);
        // deviceData = DeviceInfo.readIosDeviceInfo(iosInfo);
        // print(deviceData);
      }
      print(deviceId);
    } on PlatformException {
      deviceData = <String, dynamic>{'Error:': '获取平台版本失败.'};
    }

    if (!mounted) return;
  }

  Future<String> _onLogin(LoginData data) async {
    print('Name: ${data.name}, Password: ${data.password}');

    HttpResponse appResponse = await dio.post(Api.passwordLogin, data: {
      "mobile": data.name,
      "password": data.password,
    });
    if (appResponse.ok) {
      var token = appResponse.data?["token"] ?? '';

      var userInfo = appResponse.data?['tbUser'] ?? '';
      prefs.setString(LocalStorage.TOKEN, token);
      prefs.setString(LocalStorage.USERINFO, json.encode(userInfo));
      // Get.offAllNamed(RouteConfig.main);
      return '';
    } else {
      return appResponse.error.toString();
    }
  }

  Future<String> _onSignUp(LoginData data) async {
    return '';
  }

  Future<String> _onRecoverPassword(String name) async {
    return '';
  }

  static final FormFieldValidator<String> defaultEmailValidator = (value) {
    if (value == 'system') {
      return null;
    }
    if (!Regex.isPhone(value!)) {
      return '请输入正确手机号!';
    }
    return null;
  };
  static final FormFieldValidator<String> defaultPasswordValidator = (value) {
    if (value!.length <= 2) {
      return '密码太短!';
    }
    return null;
  };

  @override
  void initState() {
    super.initState();
    dio = Get.find<HttpClient>();
    initPlatformState();
  }

  Widget loginWidget() {
    return FlutterLogin(
      title: '悦居生活',
      onLogin: _onLogin,
      onSignup: _onSignUp,
      onRecoverPassword: _onRecoverPassword,
      userValidator: defaultEmailValidator,
      passwordValidator: defaultPasswordValidator,
      hideForgotPasswordButton: true,
      onSubmitAnimationCompleted: () => {Get.offAllNamed(RouteConfig.main)},
      hideSignUpButton: true,
      theme: LoginTheme(primaryColor: Colors.deepPurple),
      messages: LoginMessages(
        userHint: '用户名',
        passwordHint: '密码',
        confirmPasswordHint: '确认密码',
        loginButton: '登录',
        signupButton: '注册',
        forgotPasswordButton: '忘记密码?',
        recoverPasswordButton: '帮助我',
        goBackButton: '返回',
        confirmPasswordError: '密码不匹配!',
        recoverPasswordDescription: '请输入用户名',
        recoverPasswordSuccess: '密码重置成功',
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Stack(
        children: <Widget>[
          Positioned.fill(child: loginWidget()),
          Positioned(
            left: 15.0,
            top: 25.0,
            child: IconButton(
              icon: Icon(Icons.keyboard_return),
              iconSize: 50,
              color: Colors.white,
              onPressed: () {
                Get.back();
              },
            ),
          ),
        ],
      ),
    );
  }
}
